package com.fh.modules.ems.service.impl;

import com.fh.common.api.vo.PageVo;
import com.fh.common.exception.Assert;
import com.fh.common.web.impl.AbstractServiceImpl;
import com.fh.modules.ems.entity.EmsCouponTemplate;
import com.fh.modules.ems.mapper.EmsCouponTemplateMapper;
import com.fh.modules.ems.service.IEmsCouponTemplateService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;

/**
 * @Description: 优惠券模板
 * @author： code generator
 * @date： 2019-09-26
 * @version： V1.0
 */
@Service
public class EmsCouponTemplateServiceImpl extends AbstractServiceImpl<EmsCouponTemplateMapper, EmsCouponTemplate> implements IEmsCouponTemplateService {

    @Autowired
    private EmsCouponTemplateMapper emsCouponTemplateMapper;

    @Override
    public void deleteEntityByDelFlag(EmsCouponTemplate entity) {
        Assert.isTrue(entity.getPublishStatus() != 0, "只有未发布状态能删除");
        super.deleteEntityByDelFlag(entity);
    }

    @Override
    public boolean update(EmsCouponTemplate emsCouponTemplate) {
        EmsCouponTemplate old=super.getById(emsCouponTemplate.getId());
        Assert.isTrue(old.getPublishStatus()==1,"已发布优惠券不能修改");
        //TODO 领取数量大于0的要新建一个版本，老版本publishStatus改为下线
        return super.updateById(emsCouponTemplate);
    }

    @Override
    public List<EmsCouponTemplate> queryReadyCouponTemplate(Serializable memberId, PageVo pageVo) {
        PageHelper.startPage(pageVo.getPageNo(), pageVo.getPageSize(),false);
        return emsCouponTemplateMapper.queryReadyCouponTemplate(memberId);
    }

    @Override
    public void addCouponTemplateReciveCount(Serializable templateId) {
        EmsCouponTemplate emsCouponTemplate=super.getById(templateId);
        addCouponTemplateReciveCount(emsCouponTemplate);
    }

    @Override
    public void addCouponTemplateReciveCount(EmsCouponTemplate emsCouponTemplate) {
        long currentTime=System.currentTimeMillis();
        Assert.isTrue(emsCouponTemplate.getDelFlag()==1||emsCouponTemplate.getPublishStatus()!=1
                ||emsCouponTemplate.getReceiveStartTime().getTime()>currentTime
                ||emsCouponTemplate.getReceiveEndTime().getTime()<currentTime,"优惠券已失效");
        Assert.isFalse(emsCouponTemplate.getPublishCount()-emsCouponTemplate.getReceiveCount()>0,"优惠券没有了");
        emsCouponTemplate.setReceiveCount(emsCouponTemplate.getReceiveCount()+1);
        this.updateById(emsCouponTemplate);
    }

    /**
     * 查询某个类型优惠券模板列表
     * @param
     * @return
     */
    public List<EmsCouponTemplate> queryTemplateAllByType(Integer templateType){
        return  emsCouponTemplateMapper.queryTemplateAllByType(templateType);
    }
}
